/*
 * logback-spring.groovy
 * Copyright 2021 Qunhe Tech, all rights reserved.
 * Qunhe PROPRIETARY/CONFIDENTIAL, any form of usage is subject to approval.
 */

import ch.qos.logback.classic.encoder.PatternLayoutEncoder
import ch.qos.logback.classic.filter.ThresholdFilter
import ch.qos.logback.core.ConsoleAppender
import ch.qos.logback.core.rolling.RollingFileAppender
import ch.qos.logback.core.rolling.SizeAndTimeBasedFNATP
import ch.qos.logback.core.rolling.TimeBasedRollingPolicy

import static ch.qos.logback.classic.Level.DEBUG
import static ch.qos.logback.classic.Level.INFO
import static ch.qos.logback.classic.Level.WARN

def defaultPattern = $/%d - BB-MAB - %c - %p [%t] %X{logTraceId} [%C{0}:%M] - %m%n/$

// 这里会提示有spring的2个类的logger暂时无效，可以忽略
def logBase = System.getProperty("log.dir", "logs")
// 这里判断是不是本地启动
def devMode = System.getProperty("log.dir") == null

def runtimeEnvironment = devMode? "   dev   ":"prod|test"
System.print("---------------------------------------\n" +
        "------ ITool Runtime Environment ------\n" +
        "---------------"+runtimeEnvironment+"---------------\n" +
        "---------------------------------------\n"
)


[
        ["ERRLOG", "/err.log", WARN],

        ["bbMan", "/elk/bb-man.log", INFO],

        ["bbManMybatis", "/elk/bb-man-mybatis.log", INFO],

        ["bbManAuth", "/elk/bb-man-auth.log", INFO],

        ["bbManRedis", "/elk/bb-man-redis.log", INFO],

        ["bbManContext", "/elk/bb-man-context.log", INFO],

        ["bbManAli", "/elk/bb-man-ali.log", INFO],


].each { it ->
    def name = it.get(0)
    def path = it.get(1)
    def level = it.get(2)

    appender(name, RollingFileAppender) {
        append = true
        file = "${logBase}${path}"
        encoder(PatternLayoutEncoder) {
            pattern = defaultPattern
        }
        rollingPolicy(TimeBasedRollingPolicy) {
            fileNamePattern = "${logBase}${path}.%d{yyyy-MM-dd}.%i"
            maxHistory = 30
            timeBasedFileNamingAndTriggeringPolicy(SizeAndTimeBasedFNATP) {
                maxFileSize = "200mb"
            }
        }
        filter(ThresholdFilter) {
            delegate.level = level
        }
    }

    logger(name, level, [name], devMode)
}

if (devMode) {
    appender("INFO", ConsoleAppender) {
        encoder(PatternLayoutEncoder) {
            pattern = $/%date %highlight(%5level \(%file:%line\)[%method] - %msg%n)/$
        }
    }
} else {
    appender("INFO", RollingFileAppender) {
        append = true
        file = "${logBase}/elk/info.log"
        encoder(PatternLayoutEncoder) {
            pattern = defaultPattern
        }
        rollingPolicy(TimeBasedRollingPolicy) {
            fileNamePattern = "${logBase}/info.log.%d{yyyy-MM-dd}.%i"
            maxHistory = 30
            timeBasedFileNamingAndTriggeringPolicy(SizeAndTimeBasedFNATP) {
                maxFileSize = "200mb"
            }
        }
    }
}

root(INFO, ["INFO", "ERRLOG"])